import { ref } from 'vue'
import { ElMessage } from 'element-plus'

// 定义数据类型
interface DataItem {
  id: number
  itemId: string
  batchId: string
  url: string
  method: string
  category: string
  status: string
  requestData: any
  responseData: any
  ruleInfo: any
  processedAt: string
  createdAt: string
  updatedAt: string
  errorMessage: string
}

interface Statistics {
  totalBatches: number
  totalRecords: number
  todayBatches: number
  todayRecords: number
  batchByStatus: Array<{status: string, count: number}>
  dataByCategory: Array<{category: string, count: number}>
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 状态变量
const statistics = ref<Statistics>({
  totalBatches: 0,
  totalRecords: 0,
  todayBatches: 0,
  todayRecords: 0,
  batchByStatus: [],
  dataByCategory: []
})

const dataItems = ref<DataItem[]>([])
const pagination = ref<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

const loading = ref(false)

// 获取数据统计信息
const fetchDataStatistics = async () => {
  try {
    const response = await fetch('http://127.0.0.1:9001/api/v1/plugin/data/statistics')
    const result = await response.json()
    
    if (result.code === 0) {
      // 处理后端返回的数据结构，确保正确的数据类型
      const data = result.data
      statistics.value = {
        totalBatches: typeof data.totalBatches === 'number' ? data.totalBatches : 0,
        totalRecords: typeof data.totalRecords === 'number' ? data.totalRecords : 0,
        todayBatches: typeof data.todayBatches === 'number' ? data.todayBatches : 0,
        todayRecords: typeof data.todayRecords === 'number' ? data.todayRecords : 0,
        batchByStatus: Array.isArray(data.batchByStatus) ? data.batchByStatus : [],
        dataByCategory: Array.isArray(data.dataByCategory) ? data.dataByCategory : []
      }
    } else {
      ElMessage.error('获取统计信息失败: ' + result.message)
    }
  } catch (error: any) {
    ElMessage.error('获取统计信息失败: ' + error.message)
  }
}

// 获取数据项列表
const fetchDataItems = async (params: any = {}) => {
  loading.value = true
  try {
    // 参数验证
    const pageNum = params.page ? parseInt(params.page) : pagination.value.currentPage
    const size = params.pageSize ? parseInt(params.pageSize) : pagination.value.pageSize
    
    // 限制参数范围
    if (isNaN(pageNum) || pageNum < 1) {
      ElMessage.error('页码必须是正整数')
      loading.value = false
      return
    }
    
    if (isNaN(size) || size < 1 || size > 100) {
      ElMessage.error('页面大小必须是1-100之间的正整数')
      loading.value = false
      return
    }
    
    // 构建查询参数
    const queryParams = new URLSearchParams({
      page: pageNum.toString(),
      pageSize: Math.min(size, 100).toString(),
      batchId: params.batchId && typeof params.batchId === 'string' && params.batchId.length <= 100 ? params.batchId : '',
      category: params.category && typeof params.category === 'string' && 
        ['bank', 'sales_order', 'purchase_order', 'invoice', 'incoming_invoice', 'outgoing_invoice', 'announcement', 'unknown'].includes(params.category) 
        ? params.category : '',
      status: params.status && typeof params.status === 'string' && 
        ['pending', 'processed', 'failed'].includes(params.status) 
        ? params.status : ''
    })
    
    const response = await fetch(`http://127.0.0.1:9001/api/v1/plugin/data/items?${queryParams}`)
    const result = await response.json()
    
    if (result.code === 0) {
      // 注意：后端分页响应中数据列表字段名为`list`，需要映射为`items`
      dataItems.value = result.data.list
      pagination.value.total = result.data.pagination.total
      pagination.value.currentPage = result.data.pagination.page
      pagination.value.pageSize = result.data.pagination.pageSize
    } else {
      ElMessage.error('获取数据项列表失败: ' + result.message)
    }
  } catch (error: any) {
    ElMessage.error('获取数据项列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取数据项详情
const fetchDataItemDetail = async (itemId: string) => {
  try {
    // 参数验证
    if (!itemId || typeof itemId !== 'string' || itemId.length > 100) {
      ElMessage.error('数据项ID格式错误')
      return null
    }
    
    const response = await fetch(`http://127.0.0.1:9001/api/v1/plugin/data/items/${encodeURIComponent(itemId)}`)
    const result = await response.json()
    
    if (result.code === 0) {
      return result.data
    } else {
      ElMessage.error('获取数据项详情失败: ' + result.message)
      return null
    }
  } catch (error: any) {
    ElMessage.error('获取数据项详情失败: ' + error.message)
    return null
  }
}

// 重新处理数据项
const reprocessDataItem = async (itemId: string) => {
  try {
    // 参数验证
    if (!itemId || typeof itemId !== 'string' || itemId.length > 100) {
      ElMessage.error('数据项ID格式错误')
      return { success: false, message: '数据项ID格式错误' }
    }
    
    const response = await fetch(`http://127.0.0.1:9001/api/v1/plugin/data/items/${encodeURIComponent(itemId)}/reprocess`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    const result = await response.json()
    
    if (result.code === 0) {
      ElMessage.success('重新处理成功')
      return { success: true, message: result.message }
    } else {
      ElMessage.error('重新处理失败: ' + result.message)
      return { success: false, message: result.message }
    }
  } catch (error: any) {
    ElMessage.error('重新处理失败: ' + error.message)
    return { success: false, message: error.message }
  }
}

// 删除数据项
const deleteDataItem = async (itemId: string) => {
  try {
    // 参数验证
    if (!itemId || typeof itemId !== 'string' || itemId.length > 100) {
      ElMessage.error('数据项ID格式错误')
      return false
    }
    
    const response = await fetch(`http://127.0.0.1:9001/api/v1/plugin/data/items/${encodeURIComponent(itemId)}`, {
      method: 'DELETE'
    })
    const result = await response.json()
    
    if (result.code === 0) {
      ElMessage.success('删除成功')
      return true
    } else {
      ElMessage.error('删除失败: ' + result.message)
      return false
    }
  } catch (error: any) {
    ElMessage.error('删除失败: ' + error.message)
    return false
  }
}

// 导出所有功能
export function useDataManagement() {
  return {
    statistics,
    dataItems,
    pagination,
    loading,
    fetchDataStatistics,
    fetchDataItems,
    fetchDataItemDetail,
    reprocessDataItem,
    deleteDataItem
  }
}